from django.shortcuts import render,reverse
from .models import Course,CourseOrder
import os, hmac, hashlib, time
from django.conf import settings
from utils import restful
from apps.xfzauth.decorators import xfz_login_required
from django.views.decorators.csrf import csrf_exempt
from hashlib import md5
# Create your views here.

def course_index(request):
    context = {
        'courses':Course.objects.all()
    }
    return render(request,'course/course_index.html',context=context)


def course_detail(request,course_id):
    course = Course.objects.get(pk=course_id)
    context = {
        'course':course
    }
    return render(request,'course/course_detail.html',context=context)





# 根据百度云点播 token 生成规则 返回token
def course_token(request):
    file = request.GET.get('video')

    expiration_time = int(time.time()) + 2 * 60 * 60

    USER_ID = settings.BAIDU_CLOUD_USER_ID
    USER_KEY = settings.BAIDU_CLOUD_USER_KEY

    # http://ikubrkx4eyzxqtpnq1w.exp.bcevod.com/mda-jgih48dyc7anvinx/mda-jgih48dyc7anvinx.m3u8
    extension = os.path.splitext(file)[1]
    media_id = file.split('/')[-1].replace(extension, '')

    key = USER_KEY.encode('utf-8')
    message = '/{0}/{1}'.format(media_id, expiration_time).encode('utf-8')
    signature = hmac.new(key, message, digestmod=hashlib.sha256).hexdigest()
    token = '{0}_{1}_{2}'.format(signature, USER_ID, expiration_time)
    return restful.result(data={'token': token})


@xfz_login_required
def course_order(request,course_id):
    course = Course.objects.get(pk=course_id)
    order = CourseOrder.objects.create(course=course,buyer=request.user,is_status=1,amount=course.price)
    context = {
        'goods': {
            'thumbnail': course.cover_url,
            'title': course.title,
            'price': course.price
        },
        'order': order,
        # /course/notify_url/
        'notify_url': request.build_absolute_uri(reverse('course:notify_view')),
        'return_url': request.build_absolute_uri(reverse('course:course_detail',kwargs={"course_id":course.pk}))
    }
    return render(request,'course/course_order.html',context=context)
@csrf_exempt
#我们从前台表单提交必须是csrftoken 但是这是paysapi回调过来的 不可能有csrftoken
#可以通过csrf_exempt设置例外
def notify_view(request):
    orderid = request.POST.get('orderid')
    print("="*30)
    print(orderid)
    print("="*30)
    CourseOrder.objects.filter(pk=orderid).update(is_status=2)
    return restful.ok()


def course_order_key(request):
    goodsname = request.POST.get('goodsname')
    istype = request.POST.get('istype')
    notify_url = request.POST.get('notify_url')
    orderid = request.POST.get('orderid')
    orderuid = str(request.user.pk)
    price = request.POST.get('price')
    return_url = request.POST.get('return_url')
    token = settings.PAYSAPI_TOKEN
    uid = settings.PAYSAPI_UID

    key = md5((goodsname+istype+notify_url+orderid+orderuid+price+return_url+token+uid).encode('utf-8')).hexdigest()
    return restful.result(data={'key':key})